package com.flute.framework.monitor;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.flute.tools.util.SerializeUtil;

public class MonitedValueBlock implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1217747893438529901L;
	private static final String BLOCK_START = "blockstart";
	private static final String BLOCK_END = "blockend";

	private List<MonitedValue> list;

	public MonitedValueBlock() {
		this.list = new ArrayList<MonitedValue>();
	}

	public void addMonitedValue(MonitedValue value) {
		this.list.add(value);
	}

	public void addMonitedValueAtBeginning(MonitedValue value) {
		this.list.add(0, value);
	}

	public List<MonitedValue> getList() {
		return list;
	}

	public StandardDate getStartDate() {
		if (list.size() > 0) {
			return new StandardDate(list.get(0).getDate());
		}

		return new StandardDate();
	}

	public MonitedValue.MonitorLevel getLowestLevel() {
		MonitedValue.MonitorLevel level = MonitedValue.MonitorLevel.info;
		if (list.size() > 0) {
			for (MonitedValue mv : list) {
				if (mv.getLevel() == MonitedValue.MonitorLevel.error) {
					level = MonitedValue.MonitorLevel.error;
				} else if (mv.getLevel() == MonitedValue.MonitorLevel.warn
						&& level != MonitedValue.MonitorLevel.error) {
					level = MonitedValue.MonitorLevel.warn;
				}
			}
		}

		return level;
	}

	public String getKey() {
		if (list.size() > 0) {
			return list.get(0).getKey();
		}

		return "no key";
	}

	public long getEventId() {
		if (list.size() > 0) {
			return list.get(0).getEventId();
		}

		return -1;
	}

	public StandardDate getEndDate() {
		if (list.size() > 0) {
			return new StandardDate(list.get(list.size() - 1).getDate());
		}

		return new StandardDate();
	}

	public String toLogString() {
		return BLOCK_START + SerializeUtil.ObjectToByteString(this) + BLOCK_END;
	}

	public String toManualString() {
		StringBuffer sb = new StringBuffer();
		for (MonitedValue mv : list) {
			if (mv.isMessage()) {
				sb.append(new StandardDate(mv.getDate()).toDateString() + "  "
						+ mv.getLevel() + "  " + mv.getMessage());
			} else {
				sb.append(mv.toManualString());
			}
			sb.append("\n");
		}

		return sb.toString().trim();
	}

	public static MonitedValueBlock fromLogString(String logString) {
		if (logString.contains(BLOCK_START) && logString.contains(BLOCK_END)) {
			String value = logString.substring(logString.indexOf(BLOCK_START),
					logString.indexOf(BLOCK_END)).replace(BLOCK_START, "")
					.replace(BLOCK_END, "");
			return (MonitedValueBlock) SerializeUtil.ByteStringToObject(value);
		}

		return null;
	}
}
